$(function() {
    $('#link_reg').on('click', function() {
        $('.login-box').hide()
        $('.reg-box').show()
    })
    $('#link_login').on('click', function() {
        $('.login-box').show()
        $('.reg-box').hide()
    })
    let form = layui.form;
    form.verify({
        pwd: [
            /^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
        ],
        repwd: (value) => {
            let pwd = $('.reg-box [name=password]').val()
            if (pwd != value) {
                return '两次输入密码不一致'
            }
        }
    })
    let layer = layui.layer
    $('#form-reg').on('submit', (e) => {
        e.preventDefault()
        $.ajax({
            url: '/api/reg',
            method: 'POST',
            data: {
                username: $('.reg-box [name=username]').val(),
                password: $('.reg-box [name=password]').val(),
                repassword: $('.reg-box [name=repassword]').val(),
            },
            success: (res) => {
                if (res.code !== 0) {
                    return layer.msg(res.message)
                }
                layer.msg('注册成功！')
                $('#link_login').click()
            }
        })
    })
    $('#form-login').on('submit', function(e) {
        e.preventDefault()
        $.ajax({
            url: '/api/login',
            method: 'POST',
            data: $(this).serialize(),
            success: (res) => {
                if (res.code !== 0) {
                    return layer.msg('登录失败！')
                }
                layer.msg('登录成功！')
                localStorage.setItem('token', res.token)
                location.href = '/index.html'
            }
        })
    })
})